package com.l.im.strategy;


import java.util.*;

/**
 * @program: LIM
 * @description: 权重分配器
 * @author: Alex Wu
 * @createDate: 2025-04-16 15:33
 **/
public class WeightRouteStrategy implements RouteStrategy {

    /**
     * 服务格式应为 "ip:port@weight"，如 "192.168.1.1:8080@3"
     */
    @Override
    public String getServer(List<String> servers) {
        if (servers == null || servers.isEmpty()) {
            return null;
        }

        List<String> weightedList = new ArrayList<>();
        for (String entry : servers) {
            String[] parts = entry.split("@");
            String server = parts[0];
            int weight = 1;
            if (parts.length == 2) {
                try {
                    weight = Integer.parseInt(parts[1]);
                } catch (NumberFormatException e) {
                    weight = 1; // 默认权重
                }
            }
            for (int i = 0; i < weight; i++) {
                weightedList.add(server);
            }
        }
        if (weightedList.isEmpty()) {
            return null;
        }

        Random random = new Random();
        return weightedList.get(random.nextInt(weightedList.size()));
    }
}
